package com.dgut.softproject.service.impl;

import com.dgut.softproject.service.BaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Example;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

@Slf4j
public class BaseServiceImpl<T, ID> implements BaseService<T, ID> {

    private JpaRepository<T, ID> jpaRepository;

    public void setJpaRepository(JpaRepository<T, ID> jpaRepository) {
        this.jpaRepository = jpaRepository;
    }


    @Override
    public T save(T entity) {
        return jpaRepository.save(entity);
    }

    @Override
    public void deleteById(ID id) {
        jpaRepository.deleteById(id);
    }

    @Override
    public T updateById(T entity) {
        // 如果没有注入baseMapper，那就不实现动态更新
        /*if(baseMapper == null){
            log.debug("当前进行的为更新所有字段");
            return save(entity);
        }
        log.debug("当前进行的为更新非null字段");
        T target = jpaRepository.findById(id).get();
        baseMapper.copy(entity, target);
        return jpaRepository.save(target);*/
        return jpaRepository.save(entity);
    }

    @Override
    public T findOne(T entity) {
        return jpaRepository.findOne(Example.of(entity)).orElse(null);
    }

    @Override
    public T findById(ID id) {
        return jpaRepository.findById(id).orElse(null);
    }

    @Override
    public List<T> findAll() {
        return jpaRepository.findAll();
    }

    @Override
    public Boolean exist(T entity) {
        return jpaRepository.exists(Example.of(entity));
    }

    @Override
    public Boolean existById(ID id) {
        return jpaRepository.existsById(id);
    }

}
